from fdfs_client.client import Fdfs_client

from django.conf import settings
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework import status
from meiduo_admin.image.image_serializers import ImageSerializers, SKUSimpleSerializer
from meiduo_admin.user.my_pagination import MyNumberPagination
from goods.models import SKUImage, SKU


# 图片管理
class ImageViewSet(ModelViewSet):
    pagination_class = MyNumberPagination
    serializer_class = ImageSerializers
    queryset = SKUImage.objects.all().order_by('-create_time')

    def create(self, request, *args, **kwargs):
        dict_data = request.data
        sku = dict_data.get("sku")
        image = dict_data.get("image")

        if not all([sku, image]):
            return Response(status=status.HTTP_400_BAD_REQUEST)

        client = Fdfs_client(settings.FDDS_CIENT)  # 上传
        result = client.upload_by_buffer(image.read())
        # 判断是否上传成功
        if result["Status"] != "Upload successed.":
            return Response(status=status.HTTP_400_BAD_REQUEST)
        image_name = result["Remote file_id"]
        image_name = image_name.replace('\\', '/')
        SKUImage.objects.create(sku_id=sku, image=image_name)
        SKU.objects.filter(id=sku, default_image_url='').update(default_image_url=image_name)

        # img_url = settings.BASE_URL + result["Remote file_id"]

        return Response(status=status.HTTP_201_CREATED)

    def update(self, request, *args, **kwargs):

        dict_data = request.data
        sku = dict_data.get("sku")
        image = dict_data.get("image")
        sku_image = self.get_object()  # 根据PK 获取Image对象

        if not all([sku, image, sku_image]):
            return Response(status=status.HTTP_400_BAD_REQUEST)

        client = Fdfs_client(settings.FDDS_CIENT)  # 上传
        result = client.upload_by_buffer(image.read())
        # 判断是否上传成功
        if result["Status"] != "Upload successed.":
            return Response(status=status.HTTP_400_BAD_REQUEST)
        image_name = result["Remote file_id"]
        SKUImage.objects.filter(id=sku_image.id).update(sku_id=sku, image=image_name)
        SKU.objects.filter(id=sku, default_image_url=sku_image.image).update(default_image_url=image_name)

        # img_url = settings.BASE_URL + result["Remote file_id"]

        return Response(status=status.HTTP_201_CREATED)


class ImageSimpleView(ListAPIView):
    pagination_class = None
    serializer_class = SKUSimpleSerializer
    queryset = SKU.objects.all()
